import {Form, Modal, Row, Col, Input} from 'antd';
import {useEffect} from 'react';
import {connect} from 'umi';
import styles from "../styles.less";

const TriggerJobForm = (props) => {
  const {dispatch, submitting} = props;
  const {triggerJobForm, setTriggerJobForm, tablePayload, setTablePayload} = props.data;
  const [form] = Form.useForm();

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });
      dispatch({
        type: 'PMonitorXxlJob/trigger',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setTriggerJobForm(undefined);
    form.resetFields();
  }

  /* 初始化表单数据 */
  useEffect(() => {
    if (triggerJobForm && triggerJobForm.data) {
      form.setFieldsValue({id: triggerJobForm.data.id});
    }
  }, [triggerJobForm, form]);

  return (
    <Modal
      confirmLoading={submitting}
      title={triggerJobForm ? triggerJobForm.title : ''}
      open={triggerJobForm ? triggerJobForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={600}
      className={styles.myModal}
    >
      <Form layout='horizontal' labelCol={{span: 5}} form={form}>
        {triggerJobForm && triggerJobForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='executorParam' label='任务参数'
              rules={[
                {required: false, message: '任务参数不能为空'},
              ]}>
              <Input.TextArea placeholder='请输入任务参数'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name='addressList' label='机器地址'
              rules={[
                {required: false, message: '机器地址不能为空'},
              ]}>
              <Input.TextArea placeholder='请输入机器地址'/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Modal>
  );
};


export default connect(({loading}) => {
  return {
    submitting: loading.effects['PMonitorXxlJob/trigger'],
  };
})(TriggerJobForm);

